package com.macaline.framemarker.db;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程数据库
 */
public class ThreadDB implements IDB {
    AtomicInteger atomicNum = new AtomicInteger(0);
    DBMap dbMap = new DBMap(); // 数据操作类
    ReentrantLock lock = new ReentrantLock(); // 锁

    {
        try {
            for (int i = 1; i <= 5; i++) {
                dbMap.insert(i + "", new HashMap<>());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public List<Map<String, Object>> select(String tabName) throws Exception {
        if(atomicNum.incrementAndGet() > 10){
            throw new Exception("已达到最大线程访问数");
        }
        List<Map<String, Object>> res = null;
        try {
            System.out.println(Thread.currentThread().getName() + "查询数据,表明：" + tabName);
            res = dbMap.select(tabName);
        } finally {
            atomicNum.getAndDecrement();
            return res;
        }
    }

    @Override
    public void dropTab(String tabName) {

    }

    @Override
    public Integer update(String tabName, Map<String, Object> item) {
        return null;
    }

    @Override
    public Integer insert(String tabName, Map<String, Object> item) throws Exception {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "添加数据成功");
            dbMap.insert(tabName, item);
        } finally {
            lock.unlock();
        }
        return 1;
    }

    @Override
    public Integer deleteTab(String tabName) {
        return null;
    }

    @Override
    public List<Map<String, Object>> getTable(String tabName) {
        return null;
    }

}
